//
//  XRmenu_HDAppDelegate.m
//  XRmenu-HD
//
//  Created by Gao Yan on 11-12-3.
//  Copyright 2011年 home user. All rights reserved.
//

#import "XRmenu_HDAppDelegate.h"
#import "XRRootViewController.h"
#import "UpdateViewController.h"
#import "TestVC.h"

@interface XRmenu_HDAppDelegate(Private)
- (BOOL)checkPermission:(NSString *)uuid;
- (void)initParameters;
-(void) insertMenuSortPlu;
-(void) updatePluSort;
-(void) searchFromTable;
-(void) deleteDbTable:(NSString *)tableName;
@end

@implementation XRmenu_HDAppDelegate

@synthesize window;
@synthesize rvc, uvc;
#pragma mark -
#pragma mark App启动前的准备
int instr(NSString *searchIn,NSString *searchFor, int startingAt)
{
	NSRange searchRange;
	int retVal;
	
	searchRange.location = startingAt;
	searchRange.length = [searchIn length] - startingAt;
	
	NSRange foundRange = [searchIn rangeOfString:searchFor options:0  range:searchRange];
	if(foundRange.length > 0){
		retVal = foundRange.location;
	}else{
		retVal = -1;
	}
	
	return retVal;
}
- (BOOL)checkPermission:(NSString *)uuid{    
	if(needCheckPermission){
		//return [Helper getLinsence:uuid];
        
        //获取硬件基本信息
//        NSInteger deviceType = 0;
//        DebugLog(@"Model position:%d", instr([[UIDevice currentDevice] model],@"Simulator",1));
//        if (instr([[UIDevice currentDevice] model],@"Simulator",1) >= 1) {
//            deviceType = 4; //模拟器
//        }else {
//            deviceType = 1;
//        }
//        
//        NSString *SN = [[UIDevice currentDevice] serialNumber];
//        NSString *bundleVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
//        NSString *tokenKeyPath = [[XRmenuFileManage documentPath] stringByAppendingPathComponent:@"tokenId"];
//        NSArray *tokenKey = [NSArray arrayWithContentsOfFile:tokenKeyPath];
//        NSString *tokenKeyStr = [tokenKey count] > 0 ? arrayObject(tokenKey,0) : @"unknow";
//        
//        DebugLog(@"Device Name:%@",[[UIDevice currentDevice] name]);
//        DebugLog(@"Device Type:%d",deviceType);
//        DebugLog(@"Device Model:%@",[[UIDevice currentDevice] model]);
//        DebugLog(@"Device OSVersion:%@",[[UIDevice currentDevice] systemVersion]);
//        DebugLog(@"Device SN:%@",SN);
//        DebugLog(@"Device UDID:%@",DEVICEUDID);
//        DebugLog(@"Bundel Version: %@", bundleVersion);
//        DebugLog(@"Token key: %@", tokenKeyStr);
	}else {
		return YES;
	}
}

- (void)initParameters{
    [XRmenuFileManage checkSaved];//保存UDID到配置文件里
    
    [APPSESSION initPluMenus];//初始化大类对象数组(只能执行一次)
    [APPSESSION getAllMyOrder];//查询我的点单
    
    //假如没有下载地址，默认写入一个
    NSString *testValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"download_url"];
	if (testValue == nil)
	{
        [[NSUserDefaults standardUserDefaults] setObject:@"http://192.168.8.63:8010" forKey:@"download_url"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    APPSESSION.language = @"zh-Hans";//zh-Hans
    APPSESSION.uistyle = @"default skin";
    
    //则从配置文件里获取
    NSString *filePath = [XRmenuFileManage savedataFile];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        APPSESSION.udid = [array objectAtIndex:2];
    }
}

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
	
#ifndef quickDebugModel
	[[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
										 UIRemoteNotificationTypeSound |
										 UIRemoteNotificationTypeAlert)];		
#endif
    
	// 检查程序授权
	if (![self checkPermission:DEVICEUDID]){
		exit(0);
	}    

    // 用测试数据初始化数据库
    if (kInitialDB) {
        [self insertMenuSortPlu];
    }
    [self initParameters];	// 初始化运行时参数
    [self.window addSubview:uvc.view];
    
//    // 判断是下载菜谱界面还是进入推荐菜界面
//	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"update_switch"]) {//update_switch
//		[self.window addSubview:uvc.view];//进入菜谱下载界面
//	}else {
//        
//		[self.window addSubview:rvc.view];//进入推荐菜界面
//	}
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{ 
	//{"aps": {"alert": "1435"}, "device_tokens": [""]}
	/*
     NSString* alert =[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; 
     UIAlertView* a =[[UIAlertView alloc] initWithTitle:@"接收到的远程信息" message:alert delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [a show]; 
     [a release]; 
	 */
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
	NSString* path =[[XRmenuFileManage documentPath] stringByAppendingPathComponent:@"tokenId"];
	
	NSString* d = [[[[deviceToken description]
					   stringByReplacingOccurrencesOfString: @"<" withString: @""]
					  stringByReplacingOccurrencesOfString: @">" withString: @""]
					 stringByReplacingOccurrencesOfString: @" " withString: @""];
	NSArray* arr =[NSArray arrayWithObject:d]; 
	[arr writeToFile:path atomically:YES];
	
	arr = [NSArray arrayWithContentsOfFile:path];
	
	/*
     UIAlertView* a =[[UIAlertView alloc] initWithTitle:@"推送TokenID" message:[arr objectAtIndex:0] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [a show];
     [a release]; 
	 */
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
	
	/*UIAlertView* a =[[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	 [a show];
	 
	 [a release];*/
	
}

- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


/**
 applicationWillTerminate: saves changes in the application\"s managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
	[[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:nil];
    
    NSError *error = nil;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            abort();
        } 
    }
	
	if (threadManagedObjectContext != nil) {
        if ([threadManagedObjectContext hasChanges] && ![threadManagedObjectContext save:&error]) {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            abort();
        } 
    }
}

-(void)applicationDidEnterBackground:(UIApplication *)application
{
}
#pragma mark -
#pragma mark Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn\"t already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext {
    
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext;
}

- (NSManagedObjectContext *)threadManagedObjectContext
{
	if (threadManagedObjectContext != nil) {
        return threadManagedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        threadManagedObjectContext = [[NSManagedObjectContext alloc] init];
        [threadManagedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return threadManagedObjectContext;
}


/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
 */
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}


/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
	NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"XRmenu_%@.sqlite", kCurrentDbNameSurfix]];
	/*
	 Set up the store.
	 For the sake of illustration, provide a pre-populated default store.
	 */
	if (!kInitialDB) {
		// If the expected store doesn't exist, copy the default store.
		if (![XRmenuFileManage fileExistByPath:storePath]) {
            DebugLog(@"不存在storePath=%@", storePath);
			NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"XRmenu_%@", kCurrentDbNameSurfix] ofType:@"sqlite"];
			if (defaultStorePath) {
                DebugLog(@"boundle里存在defalultStorePath=%@，开始复制", defaultStorePath);
				[XRmenuFileManage filesCopy:defaultStorePath TargetName:storePath];
			}
            else{
                DebugLog(@"boundle里不存在！！！defalultStorePath=%@", defaultStorePath);
            }
		}
        else{
            DebugLog(@"存在storePath=%@", storePath);
        }
	}
    	
    NSURL *storeUrl = [NSURL fileURLWithPath: storePath];
	NSError *error = nil;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }
	
    return persistentStoreCoordinator;
}

#pragma mark -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    
    [managedObjectContext release];
	[threadManagedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    
	[rvc release];
	rvc = nil;
	
	[uvc release];
	uvc = nil;
	
    [window release];
    [super dealloc];
}

#pragma mark -
#pragma mark 系统数据库测试数据初始化代码
-(void) insertMenuSortPlu{
    NSManagedObjectContext *MOC = [self managedObjectContext];
    NSString *tableName=@"PluMenu";
    DebugLog(@"-------开始更新%@-------",tableName);
    NSArray *arrayPluMenu=[[NSArray alloc] initWithObjects:@"美食广场",@"包厢",@"汤羹",@"主食",@"点心",@"粤菜", nil];
    int i=0;
    for (NSString *str in arrayPluMenu) {
        i++;
        PluMenu *plumenu = [NSEntityDescription insertNewObjectForEntityForName:tableName inManagedObjectContext:MOC];
        [plumenu setPmPluCount:num(4)];//小类的数量
        [plumenu setPmDescripts:[NSString stringWithFormat:@"{\"zh-Hans\":\"%@\",\"en\":\"meishiguangchang\"}", str]];//描述
        [plumenu setPmPccode:@"001"];//营业点编号
        [plumenu setPmPluMenuId:[NSString stringWithFormat:@"menuPicPath_%d",i]];//大类默认图片
        [plumenu setPmCode:[NSString stringWithFormat:@"0%d",i]];//大类代码
        [plumenu setPmStatus:num(1)];//是否启用 0-未启用  1-启用
        
        if(i==1||i==3||i==5){
            NSArray *arrayPluSort=[[NSArray alloc] initWithObjects:@"家常炒菜",@"凉菜",@"生猛海鲜",@"香烟",@"酒水", nil];           
            NSArray *arrayPluPlu=[[NSArray alloc] initWithObjects:@"麻辣豆腐",@"空心菜",@"青椒皮蛋",@"肉丝跑蛋",@"酸菜包头鱼",@"软中华",@"雪花啤酒", nil];
            int j=0;
            for (NSString *str in arrayPluSort) {
                j++;
                
                PluSort *plusort = [NSEntityDescription insertNewObjectForEntityForName:@"PluSort" inManagedObjectContext:MOC];
                [plusort setPsPluSortId:[NSString stringWithFormat:@"sortPicPath_%d",j]];//小类默认图片
                [plusort setPsSortType:@"0"];//0-食品 1-香烟 2-酒水
                [plusort setPsSort:[NSString stringWithFormat:@"%@00%d",plumenu.pmCode,j]];//菜类代码
                [plusort setPsCode:plumenu.pmCode];//大类代码
                [plusort setPsPluCount:num([arrayPluPlu count])];//该类下的菜品数量
                [plusort setPsDescripts:[NSString stringWithFormat:@"{\"zh-Hans\":\"%@\",\"en\":\"lengcai\"}", str]];//菜类描述
                [plusort setPsSequence:num(j)];
                [plusort setPsStatus:num(1)];//是否启用 0-未启用  1-启用
                [plusort setPsRemarks:@"备注测试"];
                
                [plusort setRsToPluMenu:plumenu];//建立小类与大类之间的对应关系(多对一)
                if (YES) {
                    int k=0;
                    for (NSString *str3 in arrayPluPlu) {
                        k++;
                        PluPlu *pluplu= [NSEntityDescription insertNewObjectForEntityForName:@"PluPlu" inManagedObjectContext:MOC];
                        [pluplu setValue:[NSString stringWithFormat:@"%@0%d",plusort.psSort,k] forKey:@"ppCode"];
                        [pluplu setValue:@"blue" forKey:@"ppColor"];
                        [pluplu setPpHelpCode:[NSString stringWithFormat:@"help code for pluplu_%d",k]];
                        [pluplu setPpNames:[NSString stringWithFormat:@"{\"zh-Hans\":\"%@\",\"en\":\"lengcai\"}", str3]];
                        [pluplu setPpPrice:num(68.00)];
                        [pluplu setPpUnits:@"{\"zh-Hans\":\"份\",\"en\":\"bag\"}"];
                        [pluplu setPpPluPluId:[NSString stringWithFormat:@"00%d.jpg",k]];//图片名
                        [pluplu setPpPosition:@"{{10,10},{80,80}}"];
                        [pluplu setPpRecommended:num(1)];//初始化全部为推荐菜
                        [pluplu setPpRemarks:@"pluplu的备注测试"];
                        [pluplu setPpSort:plusort.psSort];
                        [pluplu setPpStatus:num(1)];//是否启用 0-未启用  1-启用
                        [pluplu setPpType:@"0"];//0-食品 1-香烟 2-酒水
                        
                        PluFood *plufood= [NSEntityDescription insertNewObjectForEntityForName:@"PluFood" inManagedObjectContext:MOC];
                        [plufood setPfCapacity:num(500)];
                        [plufood setPfCode:pluplu.ppCode];//该编号必须和pluplu.ppCode相同
                        [plufood setPfCooks:@"{\"zh-Hans\":\"清蒸 红烧 少辣\",\"en\":\"cook test\"}"];
                        [plufood setPfFoodId:[NSString stringWithFormat:@"pluFoodPicPath_%d",k]];//图片名2
                        [plufood setPfHelpCode:pluplu.ppHelpCode];
                        [plufood setPfMeterials:@"{\"zh-Hans\":\"材料\",\"en\":\"meterials test\"}"];
                        [plufood setPfRemarks:pluplu.ppRemarks];
                        [plufood setPfUnitId:num(k)];  
                        PluCigarete *plucigarete= [NSEntityDescription insertNewObjectForEntityForName:@"PluCigarete" inManagedObjectContext:MOC];
                        [plucigarete setPcCigareteId:[NSString stringWithFormat:@"cigaretePicPath_%d",k]];//图片名2
                        [plucigarete setPcCO:num(k)];
                        [plucigarete setPcCode:pluplu.ppCode];
                        [plucigarete setPcHelpCode:pluplu.ppHelpCode];
                        [plucigarete setPcNicotine:num(k+2)];
                        [plucigarete setPcPackages:@"{\"zh-Hans\":\"软包装\",\"en\":\"soft bag\"}"];
                        [plucigarete setPcRemarks:pluplu.ppRemarks];
                        [plucigarete setPcTar:num(k+1)];
                        PluDrink *pludrink= [NSEntityDescription insertNewObjectForEntityForName:@"PluDrink" inManagedObjectContext:MOC];
                        [pludrink setPdCapacity:num(200)];
                        [pludrink setPdCode:pluplu.ppCode];
                        [pludrink setPdDrinkId:[NSString stringWithFormat:@"drinkPicPath_%d",k]];//图片名2
                        [pludrink setPdHelpCode:pluplu.ppHelpCode];
                        [pludrink setPdPlaces:@"浙江杭州"];
                        [pludrink setPdPrecision:@"53度"];
                        [pludrink setPdRemarks:pluplu.ppRemarks];
                        [pludrink setPdTempereature:@"25度"];
                        [pludrink setPdYear:@"2011"];
                        
                        [plusort addRsToPluPluObject:pluplu];//让菜库和菜类建立对应关系(一对多)
                        
                        //让菜品扩展表和菜库建立对应关系(一对一)
                        [pluplu setRsToPluFood:plufood];
                        [pluplu setRsToPluDrink:pludrink];
                        [pluplu setRsToPluCigarete:plucigarete];
                    }
                }
                
                if (j>i) {
                    break;
                }
            }
        }
    }
    XRmenuError *error1 = nil;
    if ([MOC save:&error1]) {
        DebugLog(@"%@ 更新成功",tableName);
    }else {
        DebugLog(@"%@ Error:",tableName);
    }
    DebugLog(@"-------%@更新结束-------",tableName);
}
-(void) searchFromTable{
    NSManagedObjectContext *MOC = [self managedObjectContext];
    NSArray *pluMenus = [XRmenuCoreData searchObjectsMOC:@"PluMenu" Predicate:nil SortKey:nil SortAscending:NO ManagedObjectContext:MOC];
    DebugLog(@"数据表里的记录数：%d", [pluMenus count]);
    for (PluMenu *pluMenu in pluMenus) {
        DebugLog(@"pmCode=%@,pmDescripts=%@,pmPluCount=%d", pluMenu.pmCode,pluMenu.pmDescripts,[pluMenu.rsToPluSort count]);
        for (PluSort *pluSort in pluMenu.rsToPluSort) {
            DebugLog(@"  psCode=%@,psSort=%@,psDescripts=%@,psPluCount=%d", pluSort.psCode,pluSort.psSort,pluSort.psDescripts,[pluSort.rsToPluPlu count]);
            for (PluPlu *pluPlu in pluSort.rsToPluPlu) {
                DebugLog(@"    ppCode=%@,ppNames=%@,ppSort=%@", pluPlu.ppCode,pluPlu.ppNames,pluPlu.ppSort);
            }
        }
    }
}
-(void) deleteDbTable:(NSString *)tableName{
    NSManagedObjectContext *MOC = [self managedObjectContext];   
    
    BOOL rtn = NO;
	[XRmenuCoreData deleteAllObjects:tableName ManagedObjectContext:MOC] ;
    
	NSError *error;
	if (![MOC save:&error]) {
		NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
		if(detailedErrors != nil && [detailedErrors count] > 0) {
			for(NSError* detailedError in detailedErrors) {
				DebugLog(@"  DetailedError: %@", [detailedError userInfo]);
			}
		}
		else {
			DebugLog(@"  %@", [error userInfo]);
		}
		abort();
	}else {
		rtn = YES;
	}
	
	if (rtn) {
        DebugLog(@"数据表[%@]删除成功",tableName);
    }
    else{
        DebugLog(@"数据表[%@]删除失败！！！",tableName);
    }
    
}
@end
